package Hash;

import java.util.HashSet;
import java.util.Set;

public class 快乐数 {
    public boolean isHappy(int n) {
        Set<Integer> sums = new HashSet<>();
        while (n != 1 && !sums.contains(n)) {
            sums.add(n);
            n = sum(n);
        }
        return n == 1;

        // 快慢指针法
        /*int slowRunner = n;
        int fastRunner = sum(n);
        while (fastRunner != 1 && slowRunner != fastRunner) {
            slowRunner = sum(slowRunner);
            fastRunner = sum(sum(fastRunner));
        }
        return fastRunner == 1;*/
    }

    private int sum(int n) {
        int sum = 0;
        while (n != 0) {
            sum += (n % 10) * (n % 10);
            n /= 10;
        }
        return sum;
    }
}
